package com.ics.tongdb.jcq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * @author lisiqun
 * @version V1.0
 * @Description:
 * @Company:G'YUN NETWORK TECHNOLOGY
 * @date 2020-04-13 11:37
 */
public class SocketClient {
    public static final NioSocketConnector connector = new NioSocketConnector();
    public static IoSession server = null;
    private static volatile SocketClient instance;
    public static String userQq = null;

    public SocketClient() {
    }

    static SocketClient getInstance() {
        Class var0 = SocketClient.class;
        synchronized(SocketClient.class) {
            if (instance == null) {
                System.out.println("正在初始化");
                instance = new SocketClient();
                instance.init();
            }

            return instance;
        }
    }

    public static void main(String[] args) {
//        SocketClient t = new SocketClient();
//        t.init();
        getInstance();
    }

    private void init() {
        connector.setConnectTimeoutMillis(3000L);
        connector.getSessionConfig().setReceiveBufferSize(1024);
        connector.getSessionConfig().setSendBufferSize(1024);
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(
            Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue())));
        connector.setDefaultRemoteAddress(new InetSocketAddress("47.99.244.100", 8011));
        connector.setHandler(new SocketHandler());
        connector.addListener(new IoListener() {
            public void sessionDestroyed(IoSession s) {
                while(true) {
                    if (!SocketClient.connector.isDisposed()) {
                        SocketClient.server = null;

                        try {
                            Thread.sleep(3000L);
                            ConnectFuture future = SocketClient.connector.connect();
                            future.awaitUninterruptibly();
                            IoSession session = future.getSession();
                            if (!session.isConnected()) {
                                continue;
                            }

                            SocketClient.server = session;
                            System.out.println("断线重连[" + SocketClient.connector.getDefaultRemoteAddress().getHostName() + ":" + SocketClient.connector.getDefaultRemoteAddress().getPort() + "]成功");
                            SocketMessage model = new SocketMessage(SocketAction.BIND.toString(), "1.0.4");
                            model.setCtime(new Date());
                            model.setUserQq(SocketClient.userQq);
                            SocketClient.getInstance().send(model);
                        } catch (Exception var5) {
                            System.out.println("重连服务器失败,3秒再连接一次:" + var5.getMessage());
                            continue;
                        }
                    }

                    return;
                }
            }
        });
        (new Thread(new Runnable() {
            public void run() {
                while(true) {
                    SocketClient.server = null;

                    try {
                        ConnectFuture future = SocketClient.connector.connect();
                        future.awaitUninterruptibly();
                        IoSession session = future.getSession();
                        if (session.isConnected()) {
                            SocketClient.server = session;
                            System.out.println("服务端连接成功");
                            SocketMessage model = new SocketMessage(SocketAction.BIND.toString(), "1.0.4");
                            model.setCtime(new Date());
                            model.setUserQq(SocketClient.userQq);
                            SocketClient.getInstance().send(model);
                            return;
                        }
                    } catch (RuntimeIoException var5) {
                        System.out.println("连接服务器失败,3秒再连接一次:" + var5.getMessage());

                        try {
                            Thread.sleep(3000L);
                        } catch (InterruptedException var4) {
                            var4.printStackTrace();
                        }
                    }
                }
            }
        })).start();
    }

    void send(final SocketMessage model) {
        (new Thread(new Runnable() {
            public void run() {
                try {
                    while(SocketClient.server == null || !SocketClient.server.isConnected()) {
                        Thread.sleep(1000L);
                    }

                    SocketClient.server.write(JSON.toJSONString(model, new SerializerFeature[]{SerializerFeature.WriteDateUseDateFormat}));
                    Application.CQ.logDebug("Nick", "消息已经发送到服务器");
                } catch (Exception var2) {
                    var2.printStackTrace();
                    Application.CQ.logDebug("Nick", "发送错误:" + var2);
                }

            }
        })).start();
    }

    void exit() {
        connector.dispose();
    }
}
